
import router, { asyncRoutes } from './router'
import NProgress from 'nprogress' // progress bar
import store from './store'

NProgress.configure({
  showSpinner: false
})

const whiteList = ['/login']
router.beforeEach(async(to, form, next) => {
  NProgress.start()
  const token = store.getters.token
  if (token) {
    if (to.path === '/login') {
      next('/')
      NProgress.done()
    } else {
      if (!store.getters.userinfo?.userId) {
        const { roles } = await store.dispatch('user/getUserInfo')
        const fileRoutes = asyncRoutes.filter(i => {
          return roles.menus.includes(i.name)
        })
        store.commit('user/SET_ROUTES', fileRoutes)

        router.addRoutes([...fileRoutes, { path: '*', redirect: '/404', hidden: true }])
        next(to.path)
      }
      next()
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
      NProgress.done()
    }
  }
  next()
})
router.afterEach((to, from) => {
  NProgress.done()
})
